package wservice.impl;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import wservice.Action;
import wservice.ParamHelper;
import wservice.ParamUtils;
import wservice.RequestParam;
import wservice.Result;
import wservice.Router;
import wservice.UriMapping;
import wservice.WsDispatcher;

public class WsDispatcherImpl implements WsDispatcher {
	
	private static Log log = LogFactory.getLog(WsDispatcherImpl.class);
	
	public WsDispatcherImpl() {
		utils = new ParamUtils();
	}
	
	/**
	 * url规则
	 */
	private Router router ; 
	
	/**
	 * 参数工具类
	 */
	private ParamUtils utils ; 
	
	public ParamUtils getUtils() {
		return utils;
	}

	public void setUtils(ParamUtils utils) {
		this.utils = utils;
	}

	/**
	 *   /app/module/action?a=1&b=11&accessKey=123456&timestamp=1330869783890&hmac=3233456777&random=8973
	 */
	@Override
	public Result dispatcher(HttpServletRequest request) {
		String uri = request.getRequestURI();
		if(uri != null && uri.endsWith("/")) {
			uri = uri.substring(0,uri.length()-1);
		}
		if(log.isDebugEnabled()) {
			log.debug("uri:" + uri);
		}
		Action action = UriMapping.getInstance().getActionByPath(uri);
		if(action == null) {
			return new ActionNotExsitsResult();
		}
		
		RequestParam params = ParamHelper.getRequestParam(request);
		
		if(action.authorized()) {
			
		}else {
			if(log.isDebugEnabled()) {
				log.debug("do not need authorezed check.");
			}
		}
		
		return null;
	}

	public Router getRouter() {
		return router;
	}

	public void setRouter(Router router) {
		this.router = router;
	}

	
	public static void main(String[] args) {
		System.out.println(System.currentTimeMillis());//毫秒
		System.out.println(new Random().nextInt(10000));
	}
}
